//
//  test3d.m
//  TarotTest
//
//  Created by apple on 2021/6/6.
//  Copyright © 2021 motic. All rights reserved.
//

#import "test3d.h"
#import "BasicAnimation.h"
#import "PockerView.h"

@interface test3d ()<CAAnimationDelegate>
@property (weak, nonatomic) IBOutlet UIView *myView;
@property (weak, nonatomic) IBOutlet UIButton *xipaiBtn;
@property (weak, nonatomic) IBOutlet UIButton *daluanBtn;
@property (weak, nonatomic) IBOutlet UIButton *qiepaiBtn;
@property (weak, nonatomic) IBOutlet UIButton *fapaiBtn;
// 全局点击次数
@property (nonatomic, assign) NSInteger clickCount;
@property (nonatomic, strong) UIImageView *clickImgV; //第一次点击的牌
@property (nonatomic, strong) UIImageView *clickImgV2; //第二次点击的牌
@property (nonatomic, strong) UIImageView *clickImgV3; //第三次点击的牌
@property (nonatomic, strong) NSMutableArray *tagArr;
@property (nonatomic, strong) UITapGestureRecognizer *qiepaiTap; //切牌动画点击手势

// 发牌的时候，用来判断是发牌动画还是翻牌动画
@property (nonatomic, assign) BOOL isFaPai;
// 翻牌的数组，将翻过的牌加到数组中储存起来
@property (nonatomic, strong) NSMutableArray *fanArr;
@end

@implementation test3d

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"动画特效";
    
    self.clickCount = 0;
    self.tagArr = [NSMutableArray array];
    // 发牌动画时，首先默认为发牌
    self.isFaPai = YES;
    self.fanArr = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    // 初始化一张牌，用来进入画面站位
    UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpeg"]];
    [self.myView addSubview:imgV];
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.myView);
        make.top.equalTo(self.myView).offset(300);
        make.size.mas_equalTo(CGSizeMake(100, 150));
    }];
    CATransform3D transDefault = CATransform3DIdentity;
    transDefault.m34 = - 1.0 / 500;
    transDefault = CATransform3DRotate(transDefault, M_PI / 3, 1, 0, 0);
    imgV.layer.transform = transDefault;
    
}
// 洗牌
- (IBAction)xipaiClick:(id)sender {
    
    //更改title
    self.title = @"洗牌";
    
    // 洗牌过程中，其他操作需要禁止
    self.xipaiBtn.userInteractionEnabled = NO;
    self.daluanBtn.userInteractionEnabled = NO;
    self.qiepaiBtn.userInteractionEnabled = NO;
    self.fapaiBtn.userInteractionEnabled = NO;
    // 在洗牌运动3.5秒结束后，再允许其他操作
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.xipaiBtn.userInteractionEnabled = YES;
        self.daluanBtn.userInteractionEnabled = YES;
        self.qiepaiBtn.userInteractionEnabled = YES;
        self.fapaiBtn.userInteractionEnabled = YES;
    });
    
    // 清除所有控件
    for(UIView *view in [self.myView subviews])
    {
        [view removeFromSuperview];
    }
    
    // 背景回正
    CATransform3D transDefault = CATransform3DIdentity;
    transDefault.m34 = - 1.0 / 500;
    transDefault = CATransform3DRotate(transDefault, M_PI / 3, 0, 0, 0);
    self.myView.layer.transform = transDefault;
    
    for (int i=0; i<30; i++) {
        UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpeg"]];
        [self.myView addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.myView);
            make.top.equalTo(self.myView).offset(300);
            make.size.mas_equalTo(CGSizeMake(100, 150));
        }];
        CATransform3D transDefault = CATransform3DIdentity;
        transDefault.m34 = - 1.0 / 500;
        transDefault = CATransform3DRotate(transDefault, M_PI / 3, 1, 0, 0);
        imgV.layer.transform = transDefault;
        
        if (i % 2 == 0) {
            CABasicAnimation *moveLeftStart = [CABasicAnimation animationWithKeyPath:@"position"];
            moveLeftStart.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x, self.myView.center.y)];
            moveLeftStart.toValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x-100, self.myView.center.y-100)];
            moveLeftStart.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            //创建CATransform3D默认变换矩阵
            CATransform3D transA = CATransform3DIdentity;
            transA.m34 = - 1.0 / 500;
            transA = CATransform3DRotate(transA, M_PI / 3, 1, 0, 0);
            CATransform3D transB = CATransform3DIdentity;
            transB.m34 = - 1.0 / 500;
            transB = CATransform3DRotate(transA, M_PI / 3, 0, -1, 0);
            CABasicAnimation *transformLeftStart = [CABasicAnimation animationWithKeyPath:@"transform"];
            transformLeftStart.toValue = [NSValue valueWithCATransform3D:transB];
            transformLeftStart.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
             
            CAAnimationGroup *animaGroupLeftStart = [CAAnimationGroup animation];
            animaGroupLeftStart.duration = 1.0f;
            animaGroupLeftStart.fillMode = kCAFillModeForwards;
            animaGroupLeftStart.removedOnCompletion = NO;
            animaGroupLeftStart.animations = @[transformLeftStart,moveLeftStart];
            [imgV.layer addAnimation:animaGroupLeftStart forKey:@"animaGroupLeftStart"];
            
            // 牌回落开始
            CABasicAnimation *moveLeftEnd = [CABasicAnimation animationWithKeyPath:@"position"];
            moveLeftEnd.toValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x, self.myView.center.y)];
            moveLeftEnd.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x-100, self.myView.center.y-100)];
            moveLeftEnd.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            CATransform3D transC = CATransform3DIdentity;
            transC.m34 = - 1.0 / 500;
            transC = CATransform3DRotate(transC, M_PI / 3, 1, 0, 0);
            CATransform3D transD = CATransform3DIdentity;
            transD.m34 = - 1.0 / 500;
            transD = CATransform3DRotate(transC, 0, 0, 1, 0);
            
            CABasicAnimation *transformLeftEnd = [CABasicAnimation animationWithKeyPath:@"transform"];
            transformLeftEnd.toValue = [NSValue valueWithCATransform3D:transD];
            transformLeftEnd.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
             
            CAAnimationGroup *animaGroupLeftEnd = [CAAnimationGroup animation];
            animaGroupLeftEnd.beginTime = CACurrentMediaTime() + 1.0f + i*0.2f;
            animaGroupLeftEnd.duration = 0.5f;
            animaGroupLeftEnd.fillMode = kCAFillModeForwards;
            animaGroupLeftEnd.removedOnCompletion = NO;
            animaGroupLeftEnd.animations = @[transformLeftEnd,moveLeftEnd];
             
            [imgV.layer addAnimation:animaGroupLeftEnd forKey:@"animaGroupLeftEnd"];
            
        } else {
            // 右面10个
            // 移动
            CABasicAnimation *moveRightStart = [CABasicAnimation animationWithKeyPath:@"position"];
            moveRightStart.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x, self.myView.center.y)];
            moveRightStart.toValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x+100, self.myView.center.y-100)];
            moveRightStart.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            // 旋转
            CATransform3D transA = CATransform3DIdentity;
            transA.m34 = - 1.0 / 500;
            transA = CATransform3DRotate(transA, M_PI / 3, 1, 0, 0);
            CATransform3D transB = CATransform3DIdentity;
            transB.m34 = - 1.0 / 500;
            transB = CATransform3DRotate(transA, M_PI / 3, 0, 1, 0);
            CABasicAnimation *transformRightStart = [CABasicAnimation animationWithKeyPath:@"transform"];
            transformRightStart.toValue = [NSValue valueWithCATransform3D:transB];
            transformRightStart.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            CAAnimationGroup *animaGroupRightStart = [CAAnimationGroup animation];
            animaGroupRightStart.duration = 1.0f;
            animaGroupRightStart.fillMode = kCAFillModeForwards;
            animaGroupRightStart.removedOnCompletion = NO;
            animaGroupRightStart.animations = @[moveRightStart,transformRightStart];
             
            [imgV.layer addAnimation:animaGroupRightStart forKey:@"animaGroupRightStart"];
            
            // 牌回落开始
            CABasicAnimation *moveRightEnd = [CABasicAnimation animationWithKeyPath:@"position"];
            moveRightEnd.toValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x, self.myView.center.y)];
            moveRightEnd.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x+100, self.myView.center.y-100)];
            moveRightEnd.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            CATransform3D transC = CATransform3DIdentity;
            transC.m34 = - 1.0 / 500;
            transC = CATransform3DRotate(transC, M_PI / 3, 1, 0, 0);
            CATransform3D transD = CATransform3DIdentity;
            transD.m34 = - 1.0 / 500;
            transD = CATransform3DRotate(transC, 0, 0, 1, 0);
            CABasicAnimation *transformRightEnd = [CABasicAnimation animationWithKeyPath:@"transform"];
            transformRightEnd.toValue = [NSValue valueWithCATransform3D:transD];
            transformRightEnd.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            
            CAAnimationGroup *animaGroupRightEnd = [CAAnimationGroup animation];
            animaGroupRightEnd.beginTime = CACurrentMediaTime() + 1.0f + i*0.2f;
            animaGroupRightEnd.duration = 0.5f;
            animaGroupRightEnd.fillMode = kCAFillModeForwards;
            animaGroupRightEnd.removedOnCompletion = NO;
            animaGroupRightEnd.animations = @[moveRightEnd,transformRightEnd];
             
            [imgV.layer addAnimation:animaGroupRightEnd forKey:@"animaGroupRightEnd"];
        }
    }
}
// 打乱
- (IBAction)daluanClick:(id)sender {
    
    //更改title
    self.title = @"打乱牌张";
    
    // 打乱过程中，其他操作需要禁止
    self.xipaiBtn.userInteractionEnabled = NO;
    self.daluanBtn.userInteractionEnabled = NO;
    self.qiepaiBtn.userInteractionEnabled = NO;
    self.fapaiBtn.userInteractionEnabled = NO;
    // 在打乱运动5秒结束后，再允许其他操作
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.xipaiBtn.userInteractionEnabled = YES;
        self.daluanBtn.userInteractionEnabled = YES;
        self.qiepaiBtn.userInteractionEnabled = YES;
        self.fapaiBtn.userInteractionEnabled = YES;
    });
    
    // 清除所有控件
    for(UIView *view in [self.myView subviews])
    {
        [view removeFromSuperview];
    }
    
    CATransform3D transDefault = CATransform3DIdentity;
    transDefault.m34 = - 1.0 / 500;
    transDefault = CATransform3DRotate(transDefault, M_PI / 3, 1, 0, 0);
    self.myView.layer.transform = transDefault;
    
    for (int i=0; i<30; i++) {
        UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpeg"]];
        [self.myView addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.myView);
            make.top.equalTo(self.myView).offset(300);
            make.size.mas_equalTo(CGSizeMake(100, 150));
        }];
        
        // 第一步： 缩小
        POPBasicAnimation *scaleSmall = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerSize];
        scaleSmall.toValue = [NSValue valueWithCGSize:CGSizeMake(50, 100)];
        scaleSmall.duration = 0.5;
        [imgV.layer pop_addAnimation:scaleSmall forKey:@"scaleSmall"];
        
        // 第二步：旋转 移动 z轴位移
        // 旋转
        POPBasicAnimation *cardRotate = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerRotation];
        cardRotate.beginTime = CACurrentMediaTime() + 0.5f;
        cardRotate.fromValue = 0;
        cardRotate.toValue = @(M_PI * (arc4random() % 30));
        cardRotate.duration = 4;
        cardRotate.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
        [imgV.layer pop_addAnimation:cardRotate forKey:@"cardRotation"];
        
        // 点移动
        float valuex = arc4random() % 450 ;
        float valuey = arc4random() % 600 ;
        POPBasicAnimation *cardMovePoint = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPosition];
        cardMovePoint.beginTime = CACurrentMediaTime() + 0.5f;
        cardMovePoint.toValue = [NSValue valueWithCGPoint:CGPointMake(valuex, valuey)];
        cardMovePoint.duration = 2;
        cardMovePoint.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [cardMovePoint setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
            if (finished) {
                POPBasicAnimation *newCardMove = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPosition];
                newCardMove.duration = 2;
                newCardMove.toValue = [NSValue valueWithCGPoint:CGPointMake(self.myView.center.x, self.myView.center.y)];
                newCardMove.timingFunction =[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                [imgV pop_addAnimation:newCardMove forKey:@"newCardMove"];
            }
        }];
        [imgV.layer pop_addAnimation:cardMovePoint forKey:@"cardMovePoint"];
        
        // z轴位移
        POPBasicAnimation *moveZ = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerTranslationZ];
        moveZ.toValue = @(random() % 20 - 20);
        moveZ.duration = 4;
        moveZ.beginTime = CACurrentMediaTime() + 0.5f;
        [imgV.layer pop_addAnimation:moveZ forKey:@"moveZ"];
        
        // 第三步： 放大
        POPBasicAnimation *scaleBig = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerSize];
        scaleBig.toValue = [NSValue valueWithCGSize:CGSizeMake(100, 150)];
        scaleBig.beginTime = CACurrentMediaTime() + 4.5f;
        scaleBig.duration = 0.5;
        [imgV.layer pop_addAnimation:scaleBig forKey:@"scaleBig"];
        
    }
}

// 切牌
- (IBAction)qiepaiClick:(id)sender {
    
    //更改title
    self.title = @"切牌";
    
    // 切牌过程中，其他操作需要禁止
    self.xipaiBtn.userInteractionEnabled = NO;
    self.daluanBtn.userInteractionEnabled = NO;
    self.qiepaiBtn.userInteractionEnabled = NO;
    self.fapaiBtn.userInteractionEnabled = NO;
    // 在切牌运动3.5秒结束后，再允许其他操作
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.xipaiBtn.userInteractionEnabled = YES;
        self.daluanBtn.userInteractionEnabled = YES;
        self.qiepaiBtn.userInteractionEnabled = YES;
        self.fapaiBtn.userInteractionEnabled = YES;
        
        // 切牌动画结束后，提示选择第一张牌
        self.title = @"请选择一张牌";
    });
    
    // 清除所有控件
    for(UIView *view in [self.myView subviews])
    {
        [view removeFromSuperview];
    }
    
    self.clickCount = 0;
    self.tagArr = [NSMutableArray array];
    self.clickImgV = NULL;
    self.clickImgV2 = NULL;
    self.clickImgV3 = NULL;
    
    // 背景倾斜
    CATransform3D transDefault = CATransform3DIdentity;
    transDefault.m34 = - 1.0 / 500;
    transDefault = CATransform3DRotate(transDefault, M_PI / 3, 1, 0, 0);
    self.myView.layer.transform = transDefault;

    // 在切牌运动3.5秒结束后，再给每张牌添加点击事件，防止切牌过程点击运动中的牌，引起动画错乱
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 添加tap手势
        self.qiepaiTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        //将手势添加至UIView中
        [self.myView addGestureRecognizer:self.qiepaiTap];
    });
    
    for (int i=0; i<3; i++) {
        UIImageView *imgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpeg"]];
        
        [self.myView addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.myView);
            make.top.equalTo(self.myView).offset(300);
            make.size.mas_equalTo(CGSizeMake(100, 150));
        }];
        
        imgV.tag = i - 1;
        NSNumber *number = [NSNumber numberWithInteger:imgV.tag];
        [self.tagArr addObject:number];
        
        // 第一步：向上抬高
        CATransform3D s1 = CATransform3DIdentity;
        s1.m34 = -1.0 / 500;
        s1 = CATransform3DTranslate(s1, 0, -100, 100); //向y轴和z轴移动
        CABasicAnimation *a_s1 = [CABasicAnimation animationWithKeyPath:@"transform"];
        a_s1.toValue = [NSValue valueWithCATransform3D:s1];
        a_s1.duration = 0.5f;
        a_s1.fillMode = kCAFillModeForwards;
        a_s1.removedOnCompletion = NO;
        [imgV.layer addAnimation:a_s1 forKey:@"a_s1"];

        // 第二步： 向右移动
        CATransform3D s2 = CATransform3DIdentity;
        s2.m34 = -1.0 / 500;
        s2 = CATransform3DTranslate(s2, 100, -100, 100); //沿x轴向右移动
        CABasicAnimation *a_s2 = [CABasicAnimation animationWithKeyPath:@"transform"];
        a_s2.toValue = [NSValue valueWithCATransform3D:s2];
        a_s2.beginTime = CACurrentMediaTime() + 0.5f;
        a_s2.duration = 0.5f;
        a_s2.fillMode = kCAFillModeForwards;
        a_s2.removedOnCompletion = NO;
        [imgV.layer addAnimation:a_s2 forKey:@"a_s2"];
        
        
        if (i == 0) {
            // 第三步： 第一张牌掉落
            CATransform3D s3 = CATransform3DIdentity;
            s3.m34 = -1.0 / 500;
            s3 = CATransform3DTranslate(s3, 100, 0, 0); //第一张牌沿y,z下落
            CABasicAnimation *a_s3 = [CABasicAnimation animationWithKeyPath:@"transform"];
            a_s3.toValue = [NSValue valueWithCATransform3D:s3];
            a_s3.beginTime = CACurrentMediaTime() + 1.0f;
            a_s3.duration = 0.5f;
            a_s3.fillMode = kCAFillModeForwards;
            a_s3.removedOnCompletion = NO;
            [imgV.layer addAnimation:a_s3 forKey:@"a_s3"];
            
        } else {
            
            // 第四步： 牌回到中间位置
            CATransform3D s4 = CATransform3DIdentity;
            s4.m34 = -1.0 / 500;
            s4 = CATransform3DTranslate(s4, 0, -100, 100); //沿x轴回去
            CABasicAnimation *a_s4 = [CABasicAnimation animationWithKeyPath:@"transform"];
            a_s4.toValue = [NSValue valueWithCATransform3D:s4];
            a_s4.beginTime = CACurrentMediaTime() + 1.5f;
            a_s4.duration = 0.5f;
            a_s4.fillMode = kCAFillModeForwards;
            a_s4.removedOnCompletion = NO;
            [imgV.layer addAnimation:a_s4 forKey:@"a_s4"];
            
            if (i == 1) {
                
                // 第五步：第二张牌掉落
                CATransform3D s5 = CATransform3DIdentity;
                s5.m34 = -1.0 / 500;
                s5 = CATransform3DTranslate(s5, 0, 0, 0); //第一张牌沿y,z下落
                CABasicAnimation *a_s5 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s5.toValue = [NSValue valueWithCATransform3D:s5];
                a_s5.beginTime = CACurrentMediaTime() + 2.0f;
                a_s5.duration = 0.5f;
                a_s5.fillMode = kCAFillModeForwards;
                a_s5.removedOnCompletion = NO;
                [imgV.layer addAnimation:a_s5 forKey:@"a_s5"];
                
            } else {
                // 第六步： 牌回到左侧
                CATransform3D s6 = CATransform3DIdentity;
                s6.m34 = -1.0 / 500;
                s6 = CATransform3DTranslate(s6, -100, -100, 100); //沿x轴回去
                CABasicAnimation *a_s6 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s6.toValue = [NSValue valueWithCATransform3D:s6];
                a_s6.beginTime = CACurrentMediaTime() + 2.5f;
                a_s6.duration = 0.5f;
                a_s6.fillMode = kCAFillModeForwards;
                a_s6.removedOnCompletion = NO;
                [imgV.layer addAnimation:a_s6 forKey:@"a_s6"];
                
                // 第七步： 最后一张牌掉
                CATransform3D s7 = CATransform3DIdentity;
                s7.m34 = -1.0 / 500;
                s7 = CATransform3DTranslate(s7, -100, 0, 0);
                CABasicAnimation *a_s7 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s7.toValue = [NSValue valueWithCATransform3D:s7];
                a_s7.beginTime = CACurrentMediaTime() + 3.0f;
                a_s7.duration = 0.5f;
                a_s7.fillMode = kCAFillModeForwards;
                a_s7.removedOnCompletion = NO;
                [imgV.layer addAnimation:a_s7 forKey:@"a_s7"];
            }
        }
    }
}
// 切牌点击事件
-(void)handleSingleTap:(UITapGestureRecognizer *)tapGesture {
    
    //如果手势点在移动view的父视图上,返回这个点.
    CGPoint touchPoint = [tapGesture locationInView:self.myView];
    
    //遍历父视图的所有子视图
    for (UIView *subView in self.myView.subviews) {
        
        //判断点是不是在移动的view上
        if ([subView.layer.presentationLayer hitTest:touchPoint]) {
            
            if (self.clickCount == 0) {
                // 第一次点击
                // 提示选择第二张牌
                self.title = @"请选择另一张牌";
                
                // 第一步：向上抬高
                CATransform3D s1 = CATransform3DIdentity;
                s1.m34 = -1.0 / 500;
                s1 = CATransform3DTranslate(s1, -100 * subView.tag, -100, 100); //向y轴和z轴移动
                CABasicAnimation *a_s1 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s1.toValue = [NSValue valueWithCATransform3D:s1];
                a_s1.duration = 0.5f;
                a_s1.fillMode = kCAFillModeForwards;
                a_s1.removedOnCompletion = NO;
                [subView.layer addAnimation:a_s1 forKey:@"a_s1"];
                
                self.clickCount ++;
                
                self.clickImgV = (UIImageView *)subView;
                
                // 删除点击的tag
                for (int i=0; i<self.tagArr.count; i++) {
                    NSNumber *n = self.tagArr[i];
                    if([n isEqual: @(subView.tag)]) {
                        [self.tagArr removeObjectAtIndex:i];
                    }
                }
                
                return;
                
            }
            if (self.clickCount == 1) {
                //第二次点击
                // 选择完第二张牌后，标题切换回去
                self.title = @"切牌";
                // 获取第二张牌
                self.clickImgV2 = (UIImageView *)subView;
                
                // 删除点击的tag
                for (int i=0; i<self.tagArr.count; i++) {
                    NSNumber *n = self.tagArr[i];
                    if([n isEqual: @(subView.tag)]) {
                        [self.tagArr removeObjectAtIndex:i];
                    }
                }
                
                // 第二步： 向右移动
                CATransform3D s2 = CATransform3DIdentity;
                s2.m34 = -1.0 / 500;
                s2 = CATransform3DTranslate(s2, -100 * self.clickImgV2.tag, -100, 100);
                CABasicAnimation *a_s2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s2.toValue = [NSValue valueWithCATransform3D:s2];
                a_s2.duration = 0.5f;
                a_s2.fillMode = kCAFillModeForwards;
                a_s2.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s2 forKey:@"a_s2"];
                
                // 第三步： 向下移动
                CATransform3D s3 = CATransform3DIdentity;
                s3.m34 = -1.0 / 500;
                s3 = CATransform3DTranslate(s3, -100 * self.clickImgV2.tag, 0, 0);
                CABasicAnimation *a_s3 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s3.toValue = [NSValue valueWithCATransform3D:s3];
                a_s3.beginTime = CACurrentMediaTime() + 0.5f;
                a_s3.duration = 0.5f;
                a_s3.fillMode = kCAFillModeForwards;
                a_s3.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s3 forKey:@"a_s3"];
                
                // 第四步：向上抬高
                CATransform3D s4 = CATransform3DIdentity;
                s4.m34 = -1.0 / 500;
                s4 = CATransform3DTranslate(s4, -100 * self.clickImgV2.tag, -100, 100); //向y轴和z轴移动
                CABasicAnimation *a_s4 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s4.toValue = [NSValue valueWithCATransform3D:s4];
                a_s4.beginTime = CACurrentMediaTime() + 1.0f;
                a_s4.duration = 0.5f;
                a_s4.fillMode = kCAFillModeForwards;
                a_s4.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s4 forKey:@"a_s4"];
                
                CATransform3D s4_2 = CATransform3DIdentity;
                s4_2.m34 = -1.0 / 500;
                s4_2 = CATransform3DTranslate(s4_2, -100 * self.clickImgV2.tag, -100, 100); //向y轴和z轴移动
                CABasicAnimation *a_s4_2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s4_2.toValue = [NSValue valueWithCATransform3D:s4_2];
                a_s4_2.beginTime = CACurrentMediaTime() + 1.0f;
                a_s4_2.duration = 0.5f;
                a_s4_2.fillMode = kCAFillModeForwards;
                a_s4_2.removedOnCompletion = NO;
                [self.clickImgV2.layer addAnimation:a_s4_2 forKey:@"a_s4_2"];
                
                // 获取到最后一张牌
                for (int i=0; i<self.myView.subviews.count; i++) {
                    UIImageView *v = (UIImageView *)self.myView.subviews[i];
                    if (v.tag == [self.tagArr[0] integerValue]) {
                        self.clickImgV3 = v;
                        break;
                    }
                }
                
                // 第五步： 向右移动
                CATransform3D s5 = CATransform3DIdentity;
                s5.m34 = -1.0 / 500;
                s5 = CATransform3DTranslate(s5, -100 * self.clickImgV3.tag, -100, 100); //沿x轴向右移动
                CABasicAnimation *a_s5 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s5.toValue = [NSValue valueWithCATransform3D:s5];
                a_s5.beginTime = CACurrentMediaTime() + 1.5f;
                a_s5.duration = 0.5f;
                a_s5.fillMode = kCAFillModeForwards;
                a_s5.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s5 forKey:@"a_s5"];
                
                CATransform3D s5_2 = CATransform3DIdentity;
                s5_2.m34 = -1.0 / 500;
                s5_2 = CATransform3DTranslate(s5_2, -100 * self.clickImgV3.tag, -100, 100); //沿x轴向右移动
                CABasicAnimation *a_s5_2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s5_2.toValue = [NSValue valueWithCATransform3D:s5_2];
                a_s5_2.beginTime = CACurrentMediaTime() + 1.5f;
                a_s5_2.duration = 0.5f;
                a_s5_2.fillMode = kCAFillModeForwards;
                a_s5_2.removedOnCompletion = NO;
                [self.clickImgV2.layer addAnimation:a_s5_2 forKey:@"a_s5_2"];
                
                // 第六步： 两张牌一起向下移动
                CATransform3D s6 = CATransform3DIdentity;
                s6.m34 = -1.0 / 500;
                s6 = CATransform3DTranslate(s6, -100 * self.clickImgV3.tag, 0, 0);
                CABasicAnimation *a_s6 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s6.toValue = [NSValue valueWithCATransform3D:s6];
                a_s6.beginTime = CACurrentMediaTime() + 2.0f;
                a_s6.duration = 0.5f;
                a_s6.fillMode = kCAFillModeForwards;
                a_s6.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s6 forKey:@"a_s6"];
                
                CATransform3D s6_2 = CATransform3DIdentity;
                s6_2.m34 = -1.0 / 500;
                s6_2 = CATransform3DTranslate(s6_2, -100 * self.clickImgV3.tag, 0, 0);
                CABasicAnimation *a_s6_2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s6_2.toValue = [NSValue valueWithCATransform3D:s6_2];
                a_s6_2.beginTime = CACurrentMediaTime() + 2.0f;
                a_s6_2.duration = 0.5f;
                a_s6_2.fillMode = kCAFillModeForwards;
                a_s6_2.removedOnCompletion = NO;
                [self.clickImgV2.layer addAnimation:a_s6_2 forKey:@"a_s6_2"];
                
                // 第七步： 回到原点
                CATransform3D s7 = CATransform3DIdentity;
                s7.m34 = -1.0 / 500;
                s7 = CATransform3DTranslate(s7, 0, 20, 0);
                CABasicAnimation *a_s7 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s7.toValue = [NSValue valueWithCATransform3D:s7];
                a_s7.beginTime = CACurrentMediaTime() + 2.5f;
                a_s7.duration = 0.5f;
                a_s7.fillMode = kCAFillModeForwards;
                a_s7.removedOnCompletion = NO;
                [self.clickImgV.layer addAnimation:a_s7 forKey:@"a_s7"];
                
                CATransform3D s7_2 = CATransform3DIdentity;
                s7_2.m34 = -1.0 / 500;
                s7_2 = CATransform3DTranslate(s7_2, 0, 20, 0);
                CABasicAnimation *a_s7_2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s7_2.toValue = [NSValue valueWithCATransform3D:s7_2];
                a_s7_2.beginTime = CACurrentMediaTime() + 2.5f;
                a_s7_2.duration = 0.5f;
                a_s7_2.fillMode = kCAFillModeForwards;
                a_s7_2.removedOnCompletion = NO;
                [self.clickImgV2.layer addAnimation:a_s7_2 forKey:@"a_s7_2"];
                
                CATransform3D s7_3 = CATransform3DIdentity;
                s7_3.m34 = -1.0 / 500;
                s7_3 = CATransform3DTranslate(s7_3, 0, 20, 0);
                CABasicAnimation *a_s7_3 = [CABasicAnimation animationWithKeyPath:@"transform"];
                a_s7_3.toValue = [NSValue valueWithCATransform3D:s7_3];
                a_s7_3.beginTime = CACurrentMediaTime() + 2.5f;
                a_s7_3.duration = 0.5f;
                a_s7_3.fillMode = kCAFillModeForwards;
                a_s7_3.removedOnCompletion = NO;
                [self.clickImgV3.layer addAnimation:a_s7_3 forKey:@"a_s7_3"];
                
                [self.myView removeGestureRecognizer:self.qiepaiTap];
            }
        }
    }
}
// 发牌
- (IBAction)fapaiClick:(id)sender {
    
    //更改title
    self.title = @"洗牌";
    
    // 洗牌过程中，其他操作需要禁止
//    self.xipaiBtn.userInteractionEnabled = NO;
//    self.daluanBtn.userInteractionEnabled = NO;
//    self.qiepaiBtn.userInteractionEnabled = NO;
//    self.fapaiBtn.userInteractionEnabled = NO;
//    // 在洗牌运动3.5秒结束后，再允许其他操作
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        self.xipaiBtn.userInteractionEnabled = YES;
//        self.daluanBtn.userInteractionEnabled = YES;
//        self.qiepaiBtn.userInteractionEnabled = YES;
//        self.fapaiBtn.userInteractionEnabled = YES;
//    });
    
    // 点击发牌的时候，将动画切换为发牌动画
    self.isFaPai = YES;
    // 清除所有控件
    for(UIView *view in [self.myView subviews])
    {
        [view removeFromSuperview];
    }
    
    // 背景回正
    CATransform3D transDefault = CATransform3DIdentity;
    transDefault.m34 = - 1.0 / 500;
    transDefault = CATransform3DRotate(transDefault, M_PI / 3, 0, 0, 0);
    self.myView.layer.transform = transDefault;
    
    // 生成20个数中不同的三个随机数
    NSMutableArray *valueArr = [NSMutableArray array];
    int countN = 3;
    for (int i=0; i<countN; i++) {
        int value = arc4random() % 20;
        for (int j=0; j<valueArr.count; j++) {
            NSString *s = valueArr[j];
            while ([s intValue] == value) {
                value = arc4random() % 20;
                j=-1;
            }
        }
        [valueArr addObject:[NSString stringWithFormat:@"%d", value]];
    }
    
    // 取出三个值
    int k = [valueArr[0] intValue];
    int v = [valueArr[1] intValue];
    int u = [valueArr[2] intValue];
    NSLog(@"随机数 %d %d %d", k, v, u);
    
    // 在切牌运动0.5秒结束后，再给每张牌添加点击事件，防止切牌过程点击运动中的牌，引起动画错乱
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 添加tap手势
        UITapGestureRecognizer *ftap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(FSingleTap:)];
        //将手势添加至UIView中
        [self.myView addGestureRecognizer:ftap];
    });
    
    NSArray *arr = @[@"3.jpg",@"3.jpg",@"3.jpg"];
    for (int i=0; i<arr.count; i++) {
        PockerView *pocker = [[PockerView alloc] init];
        pocker.tag = i;
        
        [self.myView addSubview:pocker];
        [pocker mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.myView);
            make.top.equalTo(self.myView).offset(300);
            make.size.mas_equalTo(CGSizeMake(100, 150));
        }];
        [pocker addPocker:arr[i]];
        
        // 牌倾斜
        CATransform3D transDefault = CATransform3DIdentity;
        transDefault.m34 = - 1.0 / 500;
        transDefault = CATransform3DRotate(transDefault, M_PI / 3, 1, 0, 0);
        pocker.layer.transform = transDefault;

        // 第一步： 将牌扶正
        CATransform3D f_s1 = CATransform3DIdentity;
        f_s1.m34 = - 1.0 / 500;
        f_s1 = CATransform3DRotate(transDefault, -M_PI / 3, 1, 0, 0);
        CABasicAnimation *a_s1 = [CABasicAnimation animationWithKeyPath:@"transform"];
        a_s1.duration = 0.5f;
        a_s1.toValue = [NSValue valueWithCATransform3D:f_s1];
        a_s1.fillMode = kCAFillModeForwards;
        a_s1.removedOnCompletion = NO;
        [pocker.layer addAnimation:a_s1 forKey:@"a_s1"];

        // 第二步： 将牌挪下去
        CATransform3D f_s2 = CATransform3DIdentity;
        f_s2.m34 = -1.0 / 500;
        f_s2 = CATransform3DTranslate(f_s2, 0, 300, 0);
        CABasicAnimation *a_s2 = [CABasicAnimation animationWithKeyPath:@"transform"];
        a_s2.toValue = [NSValue valueWithCATransform3D:f_s2];
        a_s2.duration = 0.5f;
        a_s2.fillMode = kCAFillModeForwards;
        a_s2.removedOnCompletion = NO;
        [pocker.layer addAnimation:a_s2 forKey:@"a_s2"];
    }
}

-(void)FSingleTap: (UITapGestureRecognizer *)tapGesture {
    
    //如果手势点在移动view的父视图上,返回这个点.
    CGPoint touchPoint = [tapGesture locationInView:self.myView];
    
    //遍历父视图的所有子视图
    for (PockerView *subView in self.myView.subviews) {
        
        //判断点是不是在移动的view上
        if ([subView.layer.presentationLayer hitTest:touchPoint]) {
            // 发牌动画
            if (self.isFaPai) {
                // 取到第一张牌
                if (subView.tag == 0) {
                    // 将第一张牌挪到左上角
                    CATransform3D p1_s = CATransform3DIdentity;
                    p1_s.m34 = -1.0 / 500;
                    p1_s = CATransform3DTranslate(p1_s, -130, -100, 0);
                    CABasicAnimation *a_p1 = [CABasicAnimation animationWithKeyPath:@"transform"];
                    a_p1.toValue = [NSValue valueWithCATransform3D:p1_s];
                    a_p1.duration = 1.0f;
                    a_p1.beginTime = CACurrentMediaTime() + 0.5f;
                    a_p1.fillMode = kCAFillModeForwards;
                    a_p1.removedOnCompletion = NO;
                    [subView.layer addAnimation:a_p1 forKey:@"a_p1"];
                }
                // 取到第二张牌
                if (subView.tag == 1) {
                    // 将第二张牌挪到中间
                    CATransform3D p2_s = CATransform3DIdentity;
                    p2_s.m34 = -1.0 / 500;
                    p2_s = CATransform3DTranslate(p2_s, 0, -100, 0);
                    CABasicAnimation *a_p2 = [CABasicAnimation animationWithKeyPath:@"transform"];
                    a_p2.toValue = [NSValue valueWithCATransform3D:p2_s];
                    a_p2.duration = 1.0f;
                    a_p2.beginTime = CACurrentMediaTime() + 1.5f;
                    a_p2.fillMode = kCAFillModeForwards;
                    a_p2.removedOnCompletion = NO;
                    [subView.layer addAnimation:a_p2 forKey:@"a_p2"];
                }
                // 取到第三张牌
                if (subView.tag == 2) {
                    // 将第三张牌挪到右上角
                    CATransform3D p3_s = CATransform3DIdentity;
                    p3_s.m34 = -1.0 / 500;
                    p3_s = CATransform3DTranslate(p3_s, 130, -100, 0);
                    CABasicAnimation *a_p3 = [CABasicAnimation animationWithKeyPath:@"transform"];
                    a_p3.toValue = [NSValue valueWithCATransform3D:p3_s];
                    a_p3.duration = 1.0f;
                    a_p3.beginTime = CACurrentMediaTime() + 2.5f;
                    a_p3.fillMode = kCAFillModeForwards;
                    a_p3.removedOnCompletion = NO;
                    [subView.layer addAnimation:a_p3 forKey:@"a_p3"];
                }
                
                // 在3秒发完牌后，将isFaPai至于false,切换为翻牌模式
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.isFaPai = NO;
                });
            }
            // 翻牌动画
            else {
                // 开始翻牌
                // 如果数组中不包含tag，证明没有被翻过，将入数组
                if (![self containsItem:self.fanArr item:[NSString stringWithFormat:@"%ld", subView.tag]]) {
                    
                    [self.fanArr addObject:[NSString stringWithFormat:@"%ld", subView.tag]];;
                }
                // 如果拍没翻，让它翻过来
                if (!subView.isOpen) {
                    [self animationWithView:subView];
                }
            }
        }
    }
}

// 判断数组中是否含有某个
-(BOOL)containsItem: (NSMutableArray *)arr item: (NSString *)tag {
    
    for (NSString *str in arr) {
        if ([str isEqualToString:tag]) {
            return YES;
        }
    }
    return NO;
}

//翻牌动画
-(void)animationWithView:(PockerView *)view {
    
    //延时方法 正在翻转的牌翻转一半的时候把它移到视图上面来
    [self performSelector:@selector(delayAction:) withObject:view afterDelay:0.5f / 2];
    
    // 翻转动画
    UIViewAnimationOptions option = UIViewAnimationOptionTransitionFlipFromLeft;
    [UIView transitionWithView:view duration:0.5f options:option animations:^{
        if (!view.isOpen) {
            [view.imgView1 removeFromSuperview];
            [view addSubview:view.imgView2];
        }
        
    } completion:^(BOOL finished) {
        view.isOpen = true;
    }];
}

//延时方法
-(void)delayAction:(UIView *)view {
    [self.myView bringSubviewToFront:view];
}

@end
